package com.hxzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.util.MarketingThreadLocalUtil;
import com.hxzy.controller.mobile.cart.req.CartAddReq;
import com.hxzy.controller.mobile.cart.req.MobileAddCartNumReq;
import com.hxzy.controller.mobile.cart.resp.MobileCartResp;
import com.hxzy.controller.mobile.login.resp.MobileLoginResp;
import com.hxzy.controller.mobile.mapstruct.MobileCartConvert;
import com.hxzy.entity.Product;
import com.hxzy.entity.ShoppingCart;
import com.hxzy.service.ProductService;
import com.hxzy.service.ShoppingCartService;
import com.hxzy.mapper.ShoppingCartMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
* @author 11452
* @description 针对表【shopping_cart(购物车)】的数据库操作Service实现
* @createDate 2023-08-28 11:54:55
*/
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart>
    implements ShoppingCartService{

    @Autowired
    private ProductService  productService;

    @Override
    public List<MobileCartResp> findByMerchantId(Long merchantId) {
        MobileLoginResp mobileLoginResp= MarketingThreadLocalUtil.mobileThreadLocal.get();

        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
        //哪一个商家
        queryWrapper.eq(ShoppingCart::getMerchantId,merchantId);
        //当前用户id
        queryWrapper.eq(ShoppingCart::getUserId,mobileLoginResp.getId());

        List<ShoppingCart> shoppingCartList = super.list(queryWrapper);
        // 转换对象

        return MobileCartConvert.INSTANCE.convert(shoppingCartList);
    }

    /**
     * 加入购物车
     * @param req
     * @return
     */
    @Override
    public Integer cartAdd(CartAddReq req) {
        //1、当前用户是谁
        MobileLoginResp mobileLoginResp = MarketingThreadLocalUtil.mobileThreadLocal.get();
        int userId=mobileLoginResp.getId();

        //2、查询（用户id,商家id,商品id）
        ShoppingCart shoppingCart = getShoppingCart(userId, req.getMerchantId(), req.getDishId());

        //3、判断购物车是否有该用户，该商家的这个商品
        if(Objects.isNull(shoppingCart)){
            shoppingCart=new ShoppingCart();
            BeanUtils.copyProperties(req,shoppingCart);
            shoppingCart.setNumber(1);
            shoppingCart.setUserId(Long.valueOf(userId));
            this.save(shoppingCart);
        }else{
            //数量+1
            shoppingCart.setNumber(shoppingCart.getNumber()+1);
            shoppingCart.setAmount(req.getAmount());
            shoppingCart.setDishFlavor(req.getDishFlavor());
            shoppingCart.setImage(req.getImage());
            shoppingCart.setName(req.getName());
            this.updateById(shoppingCart);
        }
        return shoppingCart.getNumber();
    }

    /**
     * 查询商品信息
     * @param userId 用户id
     * @param merchantId 商家ID
     * @param dishId  商品ID
     * @return
     */
    private ShoppingCart getShoppingCart(int userId, Long merchantId, Long dishId) {
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        queryWrapper.eq(ShoppingCart::getMerchantId, merchantId);
        queryWrapper.eq(ShoppingCart::getDishId, dishId);

        return this.getOne(queryWrapper);
    }

    /**
     * 向已有购物车中减少商品数量
     * @param req
     * @return
     */
    @Override
    public Integer subCarNum(MobileAddCartNumReq req) {
        //1、当前用户是谁
        MobileLoginResp mobileLoginResp = MarketingThreadLocalUtil.mobileThreadLocal.get();
        int userId=mobileLoginResp.getId();

        ShoppingCart shoppingCart = getShoppingCart(userId, req.getMerchantId(), req.getDishId());
        if(Objects.isNull(shoppingCart)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        //购物车只有一笔数据，直接删除
        if(shoppingCart.getNumber()==1){
            this.removeById(shoppingCart.getId());
            return 0;
        }else{
            ShoppingCart updateCart=new ShoppingCart();
            updateCart.setId(shoppingCart.getId());
            updateCart.setNumber( shoppingCart.getNumber()-1);
            this.updateById(updateCart);

            return updateCart.getNumber();
        }
    }

    /**
     * 向已有购物车商品增加数量
     * @param req
     * @return
     */
    @Override
    public Integer addCarNumApi(MobileAddCartNumReq req) {
        //1、当前用户是谁
        MobileLoginResp mobileLoginResp = MarketingThreadLocalUtil.mobileThreadLocal.get();
        int userId=mobileLoginResp.getId();

        ShoppingCart shoppingCart = getShoppingCart(userId, req.getMerchantId(), req.getDishId());
        if(Objects.isNull(shoppingCart)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        //2、查询当前这个商品这个商品的总库存 (有人在攻击你了)
        Product product = this.productService.getById(req.getDishId());
        if(!product.getMerchantId().equals(req.getMerchantId())){
            //做好一点，记录攻击次数，如果超过几过，限制IP  redis来做
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        //3、库存超过了购物车的数量，不能操作
        int num=shoppingCart.getNumber();
        if(product.getNum()==-1){
            num++;
        }else{
            if(num+1> product.getNum()){
               throw new ServiceException(AckCode.PRODUCT_STOCK_Insufficient);
            }
            num++;
        }
        //更新数据库的值
        ShoppingCart updateCart=new ShoppingCart();
        updateCart.setId(shoppingCart.getId());
        updateCart.setNumber( num);
        this.updateById(updateCart);

        return num;
    }

    /**
     * 清空购物车
     * @param merchantId
     * @return
     */
    @Override
    public boolean cleanCart(Long merchantId) {
        //1、当前用户是谁
        MobileLoginResp mobileLoginResp = MarketingThreadLocalUtil.mobileThreadLocal.get();
        int userId=mobileLoginResp.getId();

        this.baseMapper.clearCart(merchantId,userId);
        return true;
    }
}




